<template>
	<view class="app login">
		<view class="title" style="padding-top: 100rpx">
			<u-icon
				name="arrow-leftward"
				v-if="flag"
				style="margin: 0 0 24rpx"
				@tap="navBack"
			></u-icon>
			<text>欢迎登录！</text>
			<text class="sub">请输入手机号密码登录</text>
		</view>
		<view class="content" v-if="['pwd', 'sms'].indexOf(loginWay) > -1">
			<swiper
				disable-touch
				duration="200"
				style="height: 300rpx"
				:current="loginWay == 'pwd' ? 0 : 1"
			>
				<swiper-item>
					<view class="form-view">
						<view class="form-item form-border">
							<input
								type="text"
								class="form-input"
								v-model="form1.username"
								placeholder="用户名/手机号"
								placeholder-style="'color':'#8e8e8e'"
								:maxlength="50"
							/>
						</view>
						<view class="form-item form-border">
							<input
								type="password"
								placeholder="密码"
								class="form-input"
								v-model="form1.password"
								placeholder-style="'color':'#8e8e8e'"
								:maxlength="50"
							/>
						</view>
					</view>
				</swiper-item>
				<swiper-item>
					<view class="form-view">
						<view class="form-item form-border">
							<input
								type="text"
								class="form-input"
								placeholder="手机号"
								v-model="form1.mobile"
								placeholder-style="'color':'#8e8e8e'"
								:maxlength="50"
							/>
						</view>
						<view class="form-item form-border">
							<input
								type="number"
								class="form-input"
								v-model="form1.code"
								placeholder="请输入短信验证码"
								placeholder-style="'color':'#8e8e8e'"
								:maxlength="6"
							/>
							<vk-data-verification-code
								type="login"
								seconds="60"
								custom-style="font-size: 28rpx;"
								:mobile="form1.mobile"
								:check-user-exist="true"
								@error="codeError"
							></vk-data-verification-code>
						</view>
					</view>
				</swiper-item>
			</swiper>
			<view class="login-way-change">
				<label
					class="login-way-left"
					v-if="loginWay == 'pwd'"
					@click="savePwd = !savePwd"
				>
					<checkbox
						shape="circle"
						class="checkbox"
						active-color="#737373"
						:checked="savePwd"
					></checkbox>
					<text>记住密码</text>
				</label>
				<view class="login-way-right">
					<text v-if="loginWay == 'pwd'" @click="loginWay = 'sms'">切换验证码登录</text>
					<text v-if="loginWay == 'sms'" @click="loginWay = 'pwd'">切换账号密码登录</text>
				</view>
			</view>
			<view class="tips">
				<navigator url="./forget" open-type="navigate" style="margin-left: 20rpx">
					找回密码
				</navigator>
				<text class="center-line"> | </text>
				<navigator url="./register" open-type="navigate">注册账号</navigator>
			</view>
			<view class="submit-btn">
				<button
					type="success"
					shape="circle"
					hover-class="hover"
					class="btn success circle"
					:plain="false"
					:hair-line="false"
					:disabled="loading"
					@click="login"
				>
					登 录
				</button>
			</view>
		</view>
		<u-popup
			v-model="inviteCodePopup.show"
			border-radius="50"
			mode="bottom"
			height="600"
			blur="20"
			:mask-close-able="false"
		>
			<view class="invite-code-popup">
				<view class="invite-code-popup-title">请输入邀请码</view>
				<view class="invite-code-popup-input-border">
					<input
						type="text"
						placeholder="请输入邀请码"
						class="invite-code-popup-input"
						v-model="inviteCodePopup.value"
						placeholder-style="'color':'#8e8e8e'"
					/>
				</view>
				<view class="bind-btn">
					<u-button
						shape="circle"
						type="success"
						:loading="loading"
						@click="bindInviteCode"
					>
						绑定
					</u-button>
				</view>
				<view style="margin-top: 40rpx">
					<u-button shape="circle" :loading="loading" @click="notBindInviteCode">
						暂不绑定
					</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
var vk = uni.vk // vk依赖

export default {
	data() {
		return {
			// init请求返回的数据
			data: {},
			// 表单请求数据
			form1: {
				username: "", // 账号
				password: "", // 密码
				mobile: "", // 手机号
				code: "", // 短信验证码
				inviteCode: "" // 邀请码
			},
			loginWay: "pwd", // 登录方式 pwd：账号+密码登录 sms：手机+短信登录
			agreement: true, // 是否同意用户协议
			savePwd: true, // 是否记住密码
			platform: "", // 平台信息
			envH5: "",
			h5WeixinAppId: "",
			loading: false,
			showLogin: false,
			inviteCodePopup: { show: false, value: "" },
			// 其他登录方式 onekey 一键登录 weixin 微信登录
			loginMode: [],

			flag: false
		}
	},
	onLoad(options) {
		let pages = getCurrentPages()
		if (
			pages.length >= 2 &&
			pages[pages.length - 2].route &&
			pages[pages.length - 2].route.indexOf("login") == -1
		) {
			this.flag = true
		} else {
			this.flag = false
		}
		this.init(options)
	},
	onShow() {
		// #ifdef MP-WEIXIN
		uni.hideHomeButton()
		// #endif
	},
	methods: {
		navBack() {
			uni.navigateBack()
		},
		// 页面数据初始化函数
		init(options = {}) {
			let that = this
			console.log("init: ", options)
			that.platform = vk.pubfn.getPlatform()
			// #ifdef H5
			that.envH5 = vk.h5.getEnv()
			if (that.envH5 === "h5-weixin" && options.code) {
				that.loginWeixin(options)
			}
			// #endif
			// #ifdef MP
			// 需要先在onLoad内执行此函数
			vk.userCenter.code2SessionWeixin({
				loading: true,
				data: {
					needCache: true
				},
				success: data => {
					that.encryptedKey = data.encryptedKey
					that.showLogin = true
				}
			})
			// #endif
			// #ifdef APP-PLUS
			vk.callFunction({
				url: "client/pub.getMchInfo",
				data: {},
				success: function (data) {
					vk.setVuex("$user.mchInfo", data.mchInfo)
					if (vk.getVuex("$user.mchInfo.app.weixin_login")) {
						that.loginMode.push("weixin")
					}
					uni.preLogin({
						provider: "univerify",
						success() {
							//预登录成功
							console.log("当前环境支持本机号码一键登录")
							if (vk.getVuex("$user.mchInfo.app.onekey_login")) {
								that.loginMode.push("onekey")
								that.loginWay = "onekey"
								that.loginByUniverify()
							}
						},
						fail(res) {
							// 预登录失败
							console.log("当前环境不支持本机号码一键登录", res)
						}
					})
				}
			})
			// #endif
			that.form1.inviteCode = vk.getVuex("$user.inviteCode")
			let username = vk.getVuex("$user.login.username")
			let password = vk.getVuex("$user.login.password")
			let savePwd = vk.getVuex("$user.login.savePwd")
			let mobile = vk.getVuex("$user.login.mobile")
			if (username) {
				that.form1.username = username
			}
			if (password) {
				that.form1.password = password
			}
			if (mobile) {
				that.form1.mobile = mobile
			}
			if (typeof savePwd === "boolean") {
				that.savePwd = savePwd
			}
		},
		// 账号密码登录
		login() {
			// 防抖函数
			let that = this
			vk.pubfn.debounce(() => {
				let { loginWay, form1, agreement } = that
				if (!agreement) {
					return vk.toast("请阅读并同意用户服务及隐私协议")
				}
				if (loginWay === "pwd") {
					that.loginByPwd()
				} else if (loginWay === "sms") {
					that.loginBySms()
				}
			}, 500)
		},
		// 手机短信登录
		loginBySms() {
			let that = this
			let { form1 } = that
			let { mobile, code, inviteCode } = form1
			if (!vk.pubfn.checkStr(mobile, "mobile")) {
				return vk.toast("手机号格式错误")
			}
			if (!code) {
				return vk.toast("请输入验证码")
			}
			vk.userCenter.loginBySms({
				data: {
					mobile,
					code,
					type: "login",
					inviteCode
				},
				success: data => {
					vk.setVuex("$user.login.mobile", mobile)
					vk.toast("登陆成功!", 600, () => {
						// 跳转到首页,或页面返回
						that.loginSuccess(data)
					})
				}
			})
		},
		// 账号密码登录
		loginByPwd() {
			let that = this
			let { form1, savePwd } = that
			let { username, password } = form1
			if (username.length < 4) {
				return vk.toast("账号至少4位数")
			}
			if (!vk.pubfn.checkStr(password, "pwd")) {
				return vk.toast("密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线")
			}
			// 登录操作
			vk.userCenter.login({
				data: {
					username,
					password
				},
				//loading:false,
				success: data => {
					vk.toast("登陆成功!", 600, () => {
						// 跳转到首页,或页面返回
						if (savePwd) {
							vk.setVuex("$user.login.username", username)
							vk.setVuex("$user.login.password", password)
						} else {
							vk.setVuex("$user.login.password", "")
						}
						vk.setVuex("$user.login.savePwd", savePwd)
						that.loginSuccess(data)
					})
				}
			})
		},
		// 登录成功后的执行逻辑
		loginSuccess(data) {
			let that = this
			// 检查是否有指定跳转的页面
			let app = getApp()
			if (typeof app.init == "function") app.init()
			if (vk.navigate.originalPage) {
				vk.navigate.originalTo()
				return false
			}
			// 跳转到首页,或页面返回
			let pages = getCurrentPages()
			if (
				pages.length >= 2 &&
				pages[pages.length - 2].route &&
				pages[pages.length - 2].route.indexOf("login") == -1
			) {
				const eventChannel = that.getOpenerEventChannel()
				eventChannel.emit("loginSuccess", {})
				// 页面返回
				vk.navigateBack()
			} else {
				// 进入首页
				vk.navigateToHome()
			}
		},
		// 微信一键手机号登录
		loginByWeixinPhoneNumber(e) {
			let that = this
			let { form1, encryptedKey } = that
			let { inviteCode } = form1
			// 使用微信绑定的手机号登录/注册
			let { encryptedData, iv } = e.detail
			if (!encryptedData || !iv) {
				return false
			}
			vk.userCenter.loginByWeixinPhoneNumber({
				data: {
					encryptedData,
					iv,
					encryptedKey,
					inviteCode
				},
				success: data => {
					let needInviteCode =
						data.type === "register" &&
						!data.userInfo.inviter_lock &&
						vk.pubfn.isNull(data.userInfo.inviter_uid)
					if (needInviteCode) {
						that.inviteCodePopup.show = true
						that.inviteCodePopup.value = vk.getVuex("$user.inviteCode")
						that.inviteCodePopup.data = data
					} else {
						vk.toast("登陆成功!", 600, () => {
							// 跳转到首页,或页面返回
							that.loginSuccess(data)
						})
					}
				}
			})
		},
		// 本机号码一键登录
		loginByUniverify() {
			let that = this
			vk.userCenter.loginByUniverify({
				// 更多配置请查看 https://uniapp.dcloud.io/univerify
				univerifyStyle: {
					fullScreen: true, // 是否全屏显示(hbx3.1.5起支持全屏)，true表示全屏模式，false表示非全屏模式，默认值为false。
					backgroundColor: "#f5f5f5", // 授权页面背景颜色，默认值：#ffffff
					authButton: {
						normalColor: "#19be6b", // 授权按钮正常状态背景颜色 默认值：#3479f5
						highlightColor: "#18b566", // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
						disabledColor: "#71d5a1", // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
						textColor: "#ffffff", // 授权按钮文字颜色 默认值：#ffffff
						title: "本机号码一键登录" // 授权按钮文案 默认值：“本机号码一键登录”
					},
					privacyTerms: {
						suffix: "使用本机号码登录", // 条款后的文案 默认值：“并使用本机号码登录”
						termsColor: "#555555"
					}
				},
				data: {},
				success: data => {
					uni.closeAuthView()
					let needInviteCode =
						data.type === "register" &&
						!data.userInfo.inviter_lock &&
						vk.pubfn.isNull(data.userInfo.inviter_uid)
					if (needInviteCode) {
						that.inviteCodePopup.show = true
						that.inviteCodePopup.value = vk.getVuex("$user.inviteCode")
						that.inviteCodePopup.data = data
					} else {
						vk.toast("登陆成功!", 600, () => {
							// 跳转到首页,或页面返回
							that.loginSuccess(data)
						})
					}
				},
				fail: res => {
					console.error(res)
					uni.closeAuthView()
					if (res.code === 30002) {
						that.loginWay = "pwd"
					}
				}
			})
		},
		// 第三方登录 - 微信
		loginWeixin(data) {
			let that = this
			vk.userCenter.loginByWeixin({
				data: {
					...data,
					type: "login"
				},
				success: data => {
					let needInviteCode =
						data.type === "register" &&
						!data.userInfo.inviter_lock &&
						vk.pubfn.isNull(data.userInfo.inviter_uid)
					if (needInviteCode) {
						that.inviteCodePopup.show = true
						that.inviteCodePopup.value = vk.getVuex("$user.inviteCode")
						that.inviteCodePopup.data = data
					} else {
						vk.toast("登陆成功!", 600, () => {
							// 跳转到首页,或页面返回
							that.loginSuccess(data)
						})
					}
				}
			})
		},
		// 微信公众号授权登录
		getH5WeixinCode() {
			let appid = vk.getVuex("$app.config.service.h5weixin.appid")
			let scope = "snsapi_userinfo"
			let redirect_uri = window.location.href.split("?")[0]
			let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=login#wechat_redirect`
			window.location.href = url
		},
		bindInviteCode() {
			let that = this
			let { inviteCodePopup } = that
			if (!inviteCodePopup.value) {
				vk.toast("请输入邀请码")
				return false
			}
			vk.callFunction({
				url: "client/salesman.pub_addUserLocking",
				title: "绑定中...",
				data: {
					invite_code: inviteCodePopup.value
				},
				success: data => {
					vk.toast("绑定成功!", 600, () => {
						// 跳转到首页,或页面返回
						that.loginSuccess(that.inviteCodePopup.data)
					})
				}
			})
		},
		notBindInviteCode() {
			let that = this
			// 跳转到首页,或页面返回
			that.loginSuccess(that.inviteCodePopup.data)
		},
		codeError(res) {
			if (res.notExists) {
				let mobile = this.form1.mobile
				vk.navigateTo(`./register?mobile=${mobile}`)
			}
		}
	}
}
</script>

<style lang="scss" scoped>
@import url("./css/main.css");
.login {
	height: 100vh;
	background-color: #f5f5f5;
}

.back_icon {
	position: absolute;
	top: 20rpx;
	left: 16rpx;
}

.login-way-change {
	display: flex;
	padding: 0 48rpx 0 40rpx;
	align-items: center;
	height: 50rpx;
	.login-way-left {
		.checkbox {
			transform: scale(0.7);
		}
	}
	.login-way-right {
		flex: 1;
		text-align: right;
	}
}

.tips {
	display: flex;
	justify-content: flex-end;
	padding: 10rpx 48rpx;
	color: #3ab54a;

	.center-line {
		margin: 0 8rpx;
	}
}

.invite-code-popup {
	padding: 50rpx;
	.invite-code-popup-title {
		font-size: 34rpx;
		font-weight: bold;
		text-align: center;
	}
	.invite-code-popup-input-border {
		margin-top: 50rpx;
		border: none;
		border-radius: 2.5rem;
		-webkit-box-shadow: 0 0 60rpx 0 rgba(43, 86, 112, 0.1);
		box-shadow: 0 0 60rpx 0 rgba(43, 86, 112, 0.1);
		.invite-code-popup-input {
			flex: 1;
			text-align: left;
			font-size: 28rpx;
			padding: 0 40rpx;
			width: 100%;
			height: 100rpx;
			box-sizing: border-box;
		}
	}
	.bind-btn {
		margin-top: 60rpx;
	}
}
</style>
